//
//  ChartCell.m
//  气泡
//
//  Created by zzy on 14-5-13.
//  Copyright (c) 2014年 zzy. All rights reserved.
//

#import "ChartCell.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "PublicMacros.h"
//#import "UserModel.h"
//#import "ChatMemberEntity.h"
#import "NSString+Path.h"
//#import "UIImage+PKShortVideoPlayer.h"

//#import "Utility.h"

@interface ChartCell()
{
    AVPlayer *_player;
    AVPlayerItem *_playItem;
    AVPlayerLayer *_playerLayer;
}

@property (nonatomic,strong) UIImageView *icon; //用户头像图片
@property (nonatomic,strong) UILabel *timeAnduserName; //消息时间和用户名称
@property (nonatomic,strong) ChartContentView *currentChartView;
@property (nonatomic,strong) NSString *contentStr;

//add 2017.3.15
@property (nonatomic, strong) UILabel    *groupOtherNameLabel;//群聊时 显示的成员的名字的label
@property (nonatomic, strong) UIImageView *unReadImageView;//未读的view

@end

@implementation ChartCell
@synthesize sendStatusimageview = _sendStatusimageview;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.icon=[[UIImageView alloc]init];
        self.icon.layer.masksToBounds = YES;
        self.icon.layer.cornerRadius = 5.0;
        self.icon.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:self.icon];
        
        self.timeAnduserName = [[UILabel alloc] init];
        self.timeAnduserName.font = [UIFont systemFontOfSize:15];
        self.timeAnduserName.textColor = [UIColor grayColor];
        self.timeAnduserName.textAlignment = NSTextAlignmentCenter;
        self.timeAnduserName.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:self.timeAnduserName];
        
        self.groupOtherNameLabel = [[UILabel alloc] init];
        self.groupOtherNameLabel.font = [UIFont systemFontOfSize:13];
        self.groupOtherNameLabel.textColor = [UIColor grayColor];
        self.groupOtherNameLabel.textAlignment = NSTextAlignmentLeft;
        self.groupOtherNameLabel.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:self.groupOtherNameLabel];
        
        self.chartView = [[ChartContentView alloc] initWithFrame:CGRectZero];
        [self.contentView addSubview:self.chartView];
        
        self.unReadImageView = [[UIImageView alloc]init];
        self.unReadImageView.layer.masksToBounds = YES;
        self.unReadImageView.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:self.unReadImageView];
        
        
        //发送状态
        _sendStatusimageview = [[UIImageView alloc] init];
        _sendStatusimageview.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:_sendStatusimageview];
        
        //发送语音时使用
        self.audioButton = [[UIButton alloc] init];
        self.audioButton.backgroundColor = [UIColor clearColor];
        [self.audioButton addTarget:self action:@selector(audioButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:self.audioButton];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
//        [self addGestureRecognizer:[[UILongPressGestureRecognizer alloc]
//                                     initWithTarget:self
//                                     action:@selector(longTap:)]];
        
    }
    return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}
#pragma mark - Public methods
-(void)updateCellId:(id)number isShow:(BOOL)yesOrno
{
    NSLog(@"updateCellId ");
    if(!yesOrno)
    {
        if (self.indicatorView) {
            [self.indicatorView stopAnimating];
            [self.indicatorView removeFromSuperview];
        }
    }else{
        self.indicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.chartView.frame), CGRectGetHeight(self.chartView.frame)/2)];
        self.indicatorView.backgroundColor = [UIColor clearColor];
        self.indicatorView.color = [UIColor whiteColor];
        [self.chartView.backImageView addSubview:self.indicatorView];
        [self.indicatorView startAnimating];
    }
}
#pragma mark 重写父类方法 －－处理action事件
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    if(action ==@selector(deleteItemClicked:)){
        return YES;
    }else if (action==@selector(collectItemClicked:)){
        return YES;
    }
    return [super canPerformAction:action withSender:sender];
}
-(BOOL)canBecomeFirstResponder{
    return YES;
}
#pragma mark  UIMenuItem method

-(void)collectItemClicked:(id)sender{
    if(self.delegate && [self.delegate respondsToSelector:\
                         @selector(longTapChartCell:chartMessage:chartCellLongTapType:)]){
        [self.delegate longTapChartCell:self
                           chartMessage:_cellFrame.chartMessage
                   chartCellLongTapType:ChartCellLongTapTypeCollect];
        
    }
    
}

-(void)deleteItemClicked:(id)sender{
    if(self.delegate && [self.delegate respondsToSelector:\
                         @selector(longTapChartCell:chartMessage:chartCellLongTapType:)]){
        [self.delegate longTapChartCell:self
                           chartMessage:_cellFrame.chartMessage
                   chartCellLongTapType:ChartCellLongTapTypeDelete];
        
    }
    
}
#pragma mark - Event response
- (void)audioButtonClick:(UIButton *)btn
{
    if (_cellFrame.chartMessage.messageStyle == kMessageImage) {
        
        if (_delegate && [_delegate respondsToSelector:@selector(chartCell:tapContent:)]) {
            NSString *localFilePathName = [NSString wbChatPathWithType:kChatMsgBody_Image];
            localFilePathName = [NSString stringWithFormat:@"%@/%@",localFilePathName,_cellFrame.chartMessage.fileName];
            if ([[NSFileManager defaultManager] fileExistsAtPath:localFilePathName]) {
                [self.delegate chartCell:self tapContent:_cellFrame.chartMessage.fileName];
            }else{
                [self.delegate chartCell:self tapContent:_cellFrame.chartMessage.messageImageUrl];
            }
        }
    }else if (_cellFrame.chartMessage.messageStyle == kMessageAudio){
        //音频
        if (_delegate && [_delegate respondsToSelector:@selector(chartCell:tapContent:)]) {
            [self.delegate chartCell:self tapContent:_cellFrame.chartMessage.fileName];
        }
    }else if (_cellFrame.chartMessage.messageStyle == kMessageVideo){
        //视频
        if (_delegate && [_delegate respondsToSelector:@selector(chartCell:tapContent:)]) {
            [self.delegate chartCell:self tapContent:_cellFrame.chartMessage.fileName];
        }
    }else if (_cellFrame.chartMessage.messageStyle == kMessageCustom){
        //自定义文件类信息
        if (_delegate && [_delegate respondsToSelector:@selector(chartCell:tapContent:)]) {
            //将messageID 穿过去 去数据库实时查看
            [self.delegate chartCell:self tapContent:_cellFrame.chartMessage.messageId];
        }
    }
    
}
/**
 *  长按点击事件
 *
 *  @param longRecognizer
 */
-(void)longTap:(UILongPressGestureRecognizer *)longRecognizer
{
#warning message --  语音类的cell 不可以删除？－－or something else

    if(self.cellFrame.chartMessage.messageStyle !=kMessageAudio){
        if (longRecognizer.state == UIGestureRecognizerStateBegan) {
            [self becomeFirstResponder];
            UIMenuController *menu = [UIMenuController sharedMenuController];
            UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"删除"
                                                              action:@selector(deleteItemClicked:)];
            UIMenuItem *resendItem = [[UIMenuItem alloc] initWithTitle:@"收藏"
                                                                action:@selector(collectItemClicked:)];
            [menu setMenuItems:[NSArray arrayWithObjects:copyItem,resendItem,nil]];
            [menu setTargetRect:self.chartView.bounds inView:self.chartView];
            [menu setMenuVisible:YES animated:YES];
            
        }
    }
  
}
#pragma mark - SETTERS
-(void)setCellFrame:(ChartCellFrame *)cellFrame
{
    _cellFrame = cellFrame;
    ChartMessage *chartMessage = cellFrame.chartMessage;
    self.icon.frame = cellFrame.iconRect;
    _sendStatusimageview.frame = cellFrame.sendStatusImageViewRect;
    self.unReadImageView.frame = cellFrame.unReadRect;
    self.unReadImageView.hidden = chartMessage.isRead;
    self.groupOtherNameLabel.frame = CGRectZero;
    self.groupOtherNameLabel.hidden = YES;
    if (chartMessage.messageType == kMessageFrom) {
        self.icon.hidden = NO;
        NSString *userStr;
        if (self.isGroup) {
//            userStr = [ChatMemberEntity memberIconStrFromImAccountName:chartMessage.fromMemID];
            self.groupOtherNameLabel.frame = cellFrame.groupOtherNameRect;
            self.groupOtherNameLabel.hidden = NO;
//            self.groupOtherNameLabel.text = [ChatMemberEntity memNickNameFromImAccountName:chartMessage.fromMemID];
        }else{
            NSDictionary *dic = [ChatContactMgr fetchContactMemNameByContactId:chartMessage.fromContactID];
            userStr  = dic[@"headPath"];
        }
        
        
        [ self.icon sd_setImageWithURL:[NSURL URLWithString:userStr]
                      placeholderImage:[UIImage imageNamed:@"wode"]];
        _sendStatusimageview.hidden = YES;
               
        
    }else{
        self.unReadImageView.hidden = YES;
//        UserModel *userModel = [UserManager sharedInstance].userModel;
        [self.icon sd_setImageWithURL:[NSURL URLWithString:[UserAccountManager shareUserAccountManager].userModel.imgPath]
                     placeholderImage:[UIImage imageNamed:@"wode"]];
//
        

        
    }
    
    self.timeAnduserName.frame = cellFrame.timeAnduserNameRect;
    self.timeAnduserName.text = chartMessage.showTime;
    self.chartView.chartMessage = chartMessage;
    self.chartView.frame = cellFrame.chartViewRect;
    self.chartView.contentLabel.hidden = NO;
    self.chartView.contentTextView.hidden = NO;
    self.audioButton.frame = cellFrame.chartViewRect;
    self.audioButton.hidden = YES;
    
    [self setBackGroundImageViewImage:self.chartView
                                 from:@"chatfrom_bg_normal_new.png"
                                   to:@"chatto_bg_normal_new.png"];
    
    if (chartMessage.messageStyle == kMessageText) {
        self.unReadImageView.image = nil;
        self.unReadImageView.hidden = YES;
        self.chartView.contentLabel.hidden = YES;
        self.chartView.contentLabel.text = chartMessage.content;
//        [self bringSubviewToFront:self.chartView.contentLabel];
        
        self.chartView.contentTextView.hidden = NO;
        self.chartView.contentTextView.attributedText = chartMessage.attributedString;
        [self bringSubviewToFront:self.chartView.contentTextView];

        
        self.chartView.messageImageView.hidden = YES;
        
    }else if (chartMessage.messageStyle == kMessageImage){
        self.unReadImageView.image = nil;
        self.unReadImageView.hidden = YES;
        self.chartView.contentLabel.hidden = YES;
        self.chartView.contentTextView.hidden = YES;
        self.audioButton.hidden = NO;
        [self.audioButton setImage:nil forState:UIControlStateNormal];
        self.chartView.messageImageView.hidden = NO;
        
        NSString *localFilePathName = [NSString wbChatPathWithType:kChatMsgBody_Image];
        localFilePathName = [NSString stringWithFormat:@"%@/%@",localFilePathName,chartMessage.fileName];
        if ([[NSFileManager defaultManager] fileExistsAtPath:localFilePathName]) {
            NSFileManager* manager    = [NSFileManager defaultManager];
            NSData *imageData         = [manager contentsAtPath:localFilePathName];
            self.chartView.messageImageView.image = [UIImage imageWithData:imageData];

        }else{
            [self.chartView.messageImageView sd_setImageWithURL:[NSURL URLWithString:chartMessage.messageImageUrl]
                                               placeholderImage:[UIImage imageNamed:@"Default_DisplayImage"]];
        }
    }else if (chartMessage.messageStyle == kMessageAudio){
        
        self.chartView.contentLabel.text = [NSString stringWithFormat:@"%ld''", (long)chartMessage.duration];
        [self bringSubviewToFront:self.chartView.contentLabel];
        self.chartView.contentTextView.hidden = YES;
        self.chartView.messageImageView.hidden = NO;
        self.audioButton.hidden = NO;
        [self.audioButton setImage:nil forState:UIControlStateNormal];
        
        if (chartMessage.messageType == kMessageFrom) {
            if (chartMessage.isRead) {
                self.unReadImageView.image = nil;
                self.unReadImageView.hidden = YES;


            }else{
                self.unReadImageView.hidden = NO;
                self.unReadImageView.image = [UIImage imageNamed:@"unReadBg"];
            }
            self.chartView.messageImageView.image = [UIImage imageNamed:@"voiceThreeBg"];
            self.chartView.messageImageView.animationImages = @[[UIImage imageNamed:@"voiceOneBg"],\
                                                                [UIImage imageNamed:@"voiceTwoBg"],[UIImage imageNamed:@"voiceThreeBg"]];
            
        }else{
            self.unReadImageView.image = nil;
            self.unReadImageView.hidden = YES;
            self.chartView.messageImageView.image = [UIImage imageNamed:@"myVoiceThreeBg"];
            self.chartView.messageImageView.animationImages = @[[UIImage imageNamed:@"myVoiceOneBg"],\
                                                                [UIImage imageNamed:@"myVoiceTwoBg"],[UIImage imageNamed:@"myVoiceThreeBg"]];
        }
        
        
        self.chartView.messageImageView.animationDuration = 2.0;
        self.chartView.messageImageView.animationRepeatCount = 0;
        
    }else if (chartMessage.messageStyle == kMessageVideo){
        self.unReadImageView.image = nil;
        self.unReadImageView.hidden = YES;
        self.chartView.contentLabel.hidden = YES;
        self.chartView.contentTextView.hidden =  YES;
        self.audioButton.hidden = NO;
        self.chartView.messageImageView.hidden = NO;
        self.chartView.messageImageView.image = [self videoImageViewWithCellFrame:cellFrame];
        
        [self.audioButton setImage:[UIImage imageNamed:@"playVideoBg"] forState:UIControlStateNormal];

        
        
        
    }else if (chartMessage.messageStyle == kMessageCustom){
        self.unReadImageView.image = nil;
        self.unReadImageView.hidden = YES;
        [self setBackGroundImageViewImage:self.chartView
                                     from:@"chatfrom_bg_normal_new.png"
                                       to:@"baichatto_bg_normal_new.png"];
        self.chartView.contentLabel.hidden = YES;
        self.chartView.contentTextView.hidden = YES;
        self.chartView.messageImageView.hidden = YES;
        self.audioButton.hidden = NO;
        [self.audioButton setImage:nil forState:UIControlStateNormal];
        self.chartView.fileNameLabel.text = chartMessage.fileName;
        self.chartView.fileSizeLabel.text = [NSString stringWithFormat:@"%ld",chartMessage.fileSize];
    }
}



- (UIImage *)videoImageViewWithCellFrame:(ChartCellFrame *)cellFrame
{
#warning message -应该从个人的im相关文件夹找信息
    NSString *videopath;
    //视频
    NSString *localFilePathName = [NSString wbChatPathWithType:kChatMsgBody_Video];
    videopath = [NSString stringWithFormat:@"%@/%@",localFilePathName,cellFrame.chartMessage.fileName];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:videopath]) {
        return [UIImage imageNamed:@"videoDefaultSqureBg"];

    };
//    UIImage *image = [UIImage pk_previewImageWithVideoURL:[NSURL fileURLWithPath:videopath]];
    UIImage *image = nil;

    return image;
}


#pragma mark - Private methods
/**
 *  设置气泡的背景图片
 *
 *  @param chartView
 *  @param from
 *  @param to
 */
-(void)setBackGroundImageViewImage:(ChartContentView *)chartView from:(NSString *)from to:(NSString *)to
{
    UIImage *normal=nil ;
    if(chartView.chartMessage.messageType == kMessageFrom){
        
        normal = [UIImage imageNamed:from];
        normal = [normal stretchableImageWithLeftCapWidth:normal.size.width * 0.5 topCapHeight:normal.size.height * 0.7];
        
    }else if(chartView.chartMessage.messageType==kMessageTo){
        
        normal = [UIImage imageNamed:to];
        normal = [normal stretchableImageWithLeftCapWidth:normal.size.width * 0.5 topCapHeight:normal.size.height * 0.7];
    }
    chartView.backImageView.image=normal;
    
    if (chartView.chartMessage.messageStyle == kMessageText) {
        
    }else if (chartView.chartMessage.messageStyle == kMessageImage){
        
    }else if (chartView.chartMessage.messageStyle == kMessageAudio){
        if(chartView.chartMessage.messageType == kMessageFrom){
            chartView.messageImageView.image = [UIImage imageNamed:@"chatfrom_voice_image"];
            
        }else if(chartView.chartMessage.messageType==kMessageTo){
            chartView.messageImageView.image = [UIImage imageNamed:@"chatto_voice_image"];
        }
    }else if (chartView.chartMessage.messageStyle == kMessageVideo){
        
    }
}




@end
